package edu.je.prs.Service;

import com.alibaba.fastjson.JSON;
import com.junqson.je.common.constant.AppRedisKey;
import com.junqson.je.common.exception.BizException;
import com.junqson.je.common.model.ApiResult;
import edu.je.prs.Mapper.ResumeInfoMapper;
import edu.je.prs.util.ESUtil;
import edu.je.prs.vo.MatchPositionVo;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @Description:
 * @author: Anhlaidh
 * @date: 2021-04-20 17:55
 */
@Service
public class MatchService {
    @Autowired
    ESUtil esUtil;

    @Autowired
    ResumeInfoMapper mapper;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    FrequencyService frequencyService;

    public ApiResult matchPosition(int id) {
        HashMap<String, Integer> frequency = null;
        //获取所有频数
        String s = redisTemplate.opsForValue().get(AppRedisKey.ALL_SKILL_FREQUENCY);
        if (s == null) {
            frequency = frequencyService.getAllSkillFrequency();
        } else {
            frequency = JSON.parseObject(s, HashMap.class);
        }
        //获取tags
        String tagStr = redisTemplate.opsForValue().get(AppRedisKey.TAGS_HEADER + id);
        if (tagStr == null) {
            //TODO 从数据库拉取
            throw new BizException(500, "could not find tags");
        }
        List<String> tags = JSON.parseArray(tagStr, String.class);
        //优先级过滤
        PriorityQueue<Tag> queue = new PriorityQueue<>(new Comparator<Tag>() {
            @Override
            public int compare(Tag o1, Tag o2) {
                return o2.value - o1.value;
            }
        });
        StringBuilder matchStr = new StringBuilder();
        for (int i = 0; i < tags.size(); i++) {
            if (frequency.containsKey(tags.get(i).toLowerCase())) {
                queue.add(new Tag(tags.get(i), frequency.get(tags.get(i).toLowerCase())));

            }
        }
        for (int i = 0; i < Math.min(3, queue.size()); i++) {
            matchStr.append(queue.poll().name+" ");
        }
        //根据优先级获取hit
        SearchHits searchHits = null;
        try {
            String[] source = {"id", "name", "company", "salary"};
            searchHits = esUtil.ESMatcher(matchStr.toString(), source, "name","detail");
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (searchHits == null) {
            throw new BizException(500, "ES NotFound");
        }
        SearchHit[] hits = searchHits.getHits();
        float maxScore = searchHits.getMaxScore();
        //从hits中取值,封装
        List<MatchPositionVo> result = new ArrayList<>();
        for (int i = 0; i < hits.length; i++) {
            SearchHit hit = hits[i];

            float score = hit.getScore();
            Map<String, Object> fields = hit.getSourceAsMap();
            String name = fields.get("name").toString();
            String Vid = fields.get("id").toString();
            String company = fields.get("company").toString();
            String salary = fields.get("salary").toString();
            result.add(new MatchPositionVo(score, maxScore, Vid, name, salary, company));
        }



        return ApiResult.success(result);
    }
    static class Tag {
        String name;
        int value;

        public Tag(String name, int value) {
            this.name = name;
            this.value = value;
        }
    }


}

